import React, {Component, PropTypes} from 'react'
import fetch from 'isomorphic-fetch'
import { ContactList, SearchBar } from './'

class ContactContainer extends Component {
  constructor() {
    super(...arguments)
    this.state = {
      contacts: this.props.initialData || [],
      filterText: '',
    }
  }
  componentDidMount() {
    if (!this.props.initialData) {
      ContactContainer.requestInitialData().then(contacts => {
        console.log('0000')
        this.setState({ contacts });
      });
    }
  }
  handleUserInput(searchTerm) {
    this.setState({filterText: searchTerm})
  }
  render() {
    return(
      <div>
        <SearchBar filterText={this.state.filterText} onUserInput={this.handleUserInput.bind(this)} />
        <ContactList contacts={this.props.initialData} filterText={this.state.filterText}/>
      </div>
    )
  }
};

ContactContainer.propTypes = {
  initialData: PropTypes.any
};

ContactContainer.requestInitialData = () => {
  return fetch('http://localhost:3000/contacts.json')
  .then((response) => response.json())
}

export default ContactContainer
